<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
</head>
<body>
<p id="error"></p>
<span id = "groupid" th:text="${group.getId()}" hidden></span>
<span id="userid" th:text="${userid}" hidden></span>
群名称 :  <p th:text="${group.getGname()}" /><br/>
=====================================================<br/>
消息 :  <input id ="message" type="text" /><br/>
<button onclick="send()">发送</button><br/>
=====================================================<br/>
收到消息 :<br/>
<div id="receivedMessage">
    <div th:each="message : ${recentMessage}">
        <span th:if="${message.getUserid()} eq ${userid}">我在</span>
        <span th:if="${message.getUserid()} ne ${userid}"><span th:text="${message.getUserid()}"></span>在</span>
        <span th:text="${message.getCreatetime()}"></span>说：
        <span th:text="${message.getMessage()}"></span>
    </div>
</div>

<br/>

=====================================================<br/>
连接状态 : <button onclick="clearConnectStatu()">清空</button><br/>
<div id="connectStatu"></div><br/>

</body>

<script  type="text/javascript" src="/static/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
    var webSocket = null;
    $(function () {
        initSocket();
    });

    /**
     * 初始化websocket，建立连接
     */
    function initSocket() {
        var groupid = $("#groupid").text();
        var userid = $("#userid").text();

        if (!window.WebSocket) {
            $("#error").html(getNowFormatDate()+"  您的浏览器不支持ws<br/>");
            return false;
        }
        webSocket = new WebSocket("ws://localhost:8080/websocket/"+groupid+"/"+userid);

        // 收到服务端消息
        webSocket.onmessage = function (msg) {
            var message = JSON.parse(msg.data);
            if(1 == message.messageType){
                $("#receivedMessage").append(getNowFormatDate()+"  收到消息 : "+message.username+"上线了<br/>");
            }
            if(message.messageType ==2){
                $("#receivedMessage").append(getNowFormatDate()+"  收到消息 : "+message.username+"下线了<br/>");
            }
            if(message.messageType == 3){
                $("#receivedMessage").append(getNowFormatDate()+"  当前群组 : ");
                for(var i = 0; i< message.onlineUsers.length;i++){
                    $("#receivedMessage").append(message.onlineUsers[i]+",");
                }
                $("#receivedMessage").append("在线上<br>");
            }
            if(message.messageType == 4){
                $("#receivedMessage").append(getNowFormatDate()+"  收到来自"+message.username+"消息 : "+message.textMessage+"<br/>");
            }

        };

        // 异常
        webSocket.onerror = function (event) {
            $("#connectStatu").append(getNowFormatDate()+"  异常<br/>");
        };

        // 建立连接
        webSocket.onopen = function (event) {
            $("#connectStatu").append(getNowFormatDate()+"  建立连接成功<br/>");
        };

        // 断线重连
        webSocket.onclose = function () {
            // heartflag = false;
            // // 重试10次，每次之间间隔10秒
            // if (tryTime < 10) {
            //     setTimeout(function () {
            //         webSocket = null;
            //         tryTime++;
            //         initSocket();
            //         $("#connectStatu").append( getNowFormatDate()+"  第"+tryTime+"次重连<br/>");
            //     }, 3*1000);
            // } else {
            //     alert("重连失败.");
            // }
        };

    }

    function send(){
        var messageData = $("#message").val();
        var userid = $("#userid").text();
        var groupid = $("#groupid").text();
        var message ={
            messageData : messageData,
            userid : userid,
            groupid : groupid
        }
        webSocket.send(JSON.stringify(message));
    }

    function clearConnectStatu(){
        $("#connectStatu").empty();
    }

    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
        return currentdate;
    }

</script>
</html>